import ViewOrientation, { EOrientation } from "../Framework/scripts/ViewOrientation";
import Watcher from "../Framework/scripts/Watcher";
import Editor from "./editor/Editor";
import GameAssetMgr from "./GameAssetMgr";

const { ccclass, property } = cc._decorator;

@ccclass
export default class CookingTiledom extends cc.Component {

    /** 刷新桌面 */
    public static readonly EVENT_CREATE_ITEM = "EVENT_CREATE_ITEM";

    private itemprefab: cc.Prefab;
    private lv = 0;
    private config = [{}];

    @property(cc.Node)
    itemList: cc.Node = null;
  

    onLoad() {
        Watcher.on(GameAssetMgr.SpriteLoadedEvent, this, this.onAssetLoaded);
        Watcher.on(Editor.SET_CONFIG, this, this.setConfig);
        this.loadConfig().then(this.loadPrefabs.bind(this));

        //let widget = this.itemList.getComponent(cc.Widget);
        // Watcher.on(ViewOrientation.ON_VIEW_RESIZE, this, (info) => {
        //     if (info.dir === EOrientation.LANDSCAPE) {
        //         this.itemList.active = false;
        //         this.itemList_v.active = true;
        //     }
        //     else {
        //         this.itemList.active = true;
        //         this.itemList_v.active = false;
        //     }
        // });

    }
    async loadConfig() {
        const context = this;
        cc.loader.loadRes('config/customConfig.json', cc.JsonAsset, (err, res) => {
            if (!err) {
                context.config = res.json;
            }
        });
    }
    async loadPrefabs() {
        const context = this;
        cc.loader.loadRes('pref/item', cc.Prefab, (err, res) => {
            if (!err) {
                context.itemprefab = res;
                context.onAssetLoaded();
            }
        });
    }

    private onAssetLoaded() {
        if (!this.itemprefab || !GameAssetMgr.instance.spriteLoaded) {
            return;
        }
        console.log("配置当前场景... ...");
        this.readConfig();
    }
    setConfig(config, currentLv = 0) {
        this.lv = currentLv;
        if (config)
            this.config = config;
        this.readConfig();
    }
    readConfig() {
        //TODO 获取当前Level
        this.lv = 0; //这里默认0

        let config = this.config[this.lv];
        Watcher.dispatch(CookingTiledom.EVENT_CREATE_ITEM, config, this.itemprefab);
    }
}
